<?php

namespace apiend\modules\course\models;

use Yii;
use yii\db\Exception;
use common\models\course\CourseApplyCategory;
use common\models\base\BaseDist;
use common\logics\SmsCaptchaForm;
use common\models\course\CourseGroup;
use common\models\user\UserMeta;

/**
 * 修改群聊名称
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class GroupRenameForm extends \common\base\Model {

    /**
     * School model attributes
     */
    public $user_id;
    public $name;
    public $group_id;
    //
    private $_user;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name', 'group_id'], 'required'],
            [['name'], 'string'],
            [['group_id'], 'integer'],
            ['user_id', 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'user_id' => '用户UID',
            'contact' => '联系人',
            'mobile' => '联系电话',
        ];
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getUser() {
        return UserMeta::findOne($this->user_id);
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getGroup() {
        return CourseGroup::findOne($this->group_id);
    }

    /**
     * {@inheritdoc}
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        $group = $this->getGroup();
        if (!$user || !$group || $group->user_id !== $this->user_id) {
            $this->dumpError('您没有该操作权限');
        }
        $group->name = $this->name;
        if (!$group->save()) {
            $this->dumpError('群聊名称修改失败：' . $group->getErrorMsg());
        }

        $refreshed = Yii::$app->rongyun->transport('group')->refresh($group->id, $group->name);
        if (!$refreshed) {
            //todo
        }
        return $group;
    }

}
